<template>
  <div class="admin-schools">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>学校管理</span>
          <el-button type="primary" @click="handleAddSchool">
            添加学校
          </el-button>
        </div>
      </template>
      
      <!-- 学校列表 -->
      <el-table :data="schools" v-loading="loading">
        <el-table-column prop="name" label="学校名称" />
        <el-table-column prop="code" label="学校代码" />
        <el-table-column prop="address" label="地址" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '正常' : '限制' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150" />
        <el-table-column label="操作" width="250">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="editSchool(row)">编辑</el-button>
            <el-button
              size="small"
              :type="row.status === 1 ? 'warning' : 'success'"
              @click="toggleSchoolStatus(row)"
            >
              {{ row.status === 1 ? '限制' : '启用' }}
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteSchool(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 编辑学校对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="isEdit ? '编辑学校' : '添加学校'"
      width="500px"
    >
      <el-form :model="schoolForm" :rules="schoolRules" ref="schoolFormRef" label-width="100px">
        <el-form-item label="学校名称" prop="name">
          <el-input v-model="schoolForm.name" placeholder="请输入学校名称" />
        </el-form-item>
        <el-form-item label="学校代码" prop="code">
          <el-input v-model="schoolForm.code" placeholder="请输入学校代码" />
        </el-form-item>
        <el-form-item label="学校地址" prop="address">
          <el-input v-model="schoolForm.address" placeholder="请输入学校地址" />
        </el-form-item>
        <el-form-item label="学校描述" prop="description">
          <el-input
            v-model="schoolForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入学校描述"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="schoolForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">限制</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveSchool" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '../../utils/api'

const loading = ref(false)
const saving = ref(false)
const schools = ref([])
const editDialogVisible = ref(false)
const isEdit = ref(false)
const schoolFormRef = ref()

const schoolForm = reactive({
  id: null,
  name: '',
  code: '',
  address: '',
  description: '',
  status: 1
})

const schoolRules = {
  name: [
    { required: true, message: '请输入学校名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入学校代码', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入学校地址', trigger: 'blur' }
  ]
}

const loadSchools = async () => {
  loading.value = true
  try {
    const response = await api.get('/admin/schools')
    if (response.data.code === 200) {
      schools.value = response.data.data
    }
  } catch (error) {
    ElMessage.error('加载学校列表失败')
  } finally {
    loading.value = false
  }
}

const handleAddSchool = () => {
  isEdit.value = false
  resetForm()
  editDialogVisible.value = true
}

const editSchool = (school) => {
  isEdit.value = true
  Object.assign(schoolForm, school)
  editDialogVisible.value = true
}

const deleteSchool = async (school) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除学校"${school.name}"吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await api.delete(`/admin/schools/${school.id}`)
    if (response.data.code === 200) {
      ElMessage.success('学校删除成功')
      loadSchools()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const toggleSchoolStatus = async (school) => {
  try {
    const action = school.status === 1 ? '限制' : '启用'
    await ElMessageBox.confirm(`确定要${action}学校 ${school.name} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await api.put(`/admin/schools/${school.id}/status`, null, {
      params: { status: school.status === 1 ? 0 : 1 }
    })
    
    if (response.data.code === 200) {
      ElMessage.success(`${action}成功`)
      loadSchools()
    } else {
      ElMessage.error(response.data.message || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const saveSchool = async () => {
  if (!schoolFormRef.value) return
  
  await schoolFormRef.value.validate(async (valid) => {
    if (valid) {
      saving.value = true
      try {
        let response
        if (isEdit.value) {
          // 编辑学校
          response = await api.put(`/admin/schools/${schoolForm.id}`, schoolForm)
        } else {
          // 添加学校
          response = await api.post('/admin/schools', schoolForm)
        }
        
        if (response.data.code === 200) {
          ElMessage.success(isEdit.value ? '学校更新成功' : '学校添加成功')
          editDialogVisible.value = false
          loadSchools()
        } else {
          ElMessage.error(response.data.message || '保存失败')
        }
      } catch (error) {
        ElMessage.error('保存失败')
      } finally {
        saving.value = false
      }
    }
  })
}

const resetForm = () => {
  Object.assign(schoolForm, {
    id: null,
    name: '',
    code: '',
    address: '',
    description: '',
    status: 1
  })
  if (schoolFormRef.value) {
    schoolFormRef.value.resetFields()
  }
}

onMounted(() => {
  loadSchools()
})
</script>

<style scoped>
.admin-schools {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
